package se

import (
	"fmt"
	"os"
	"path/filepath"
)

// Size 目录或文件尺寸.
func Size(file string) int64 {
	fi, err := os.Stat(file)
	if err != nil {
		return 0
	}

	if !fi.IsDir() {
		return fi.Size()
	}

	ret := int64(0)
	_ = filepath.Walk(file, func(path string, info os.FileInfo, err error) error {
		if !info.IsDir() {
			ret += info.Size()
		}

		return nil
	})

	return ret
}

// FormatFileSize 格式化文件尺寸.
func FormatFileSize(size int64) string {
	// nolint: gomnd, ifshort
	m := int64(1024)
	if size < m {
		return fmt.Sprintf("%.0fB", float64(size)/float64(1))
	}

	if size < (m * m) {
		return fmt.Sprintf("%.0fKB", float64(size)/float64(m))
	}

	if size < (m * m * m) {
		return fmt.Sprintf("%.2fMB", float64(size)/float64(m*m))
	}

	if size < (m * m * m * m) {
		return fmt.Sprintf("%.2fGB", float64(size)/float64(m*m*m))
	}

	if size < (m * m * m * m * m) {
		return fmt.Sprintf("%.2fTB", float64(size)/float64(m*m*m*m))
	}

	return fmt.Sprintf("%.2fEB", float64(size)/float64(m*m*m*m*m))
}
